package main

import (
	"fmt"
	"time"

	"github.com/huawen0327/golee"
)

var index = func(c *golee.Context) {
	c.HTMLResponse(golee.StatusOK, "<h1>index</h1>")
}

var logger = func(c *golee.Context) {
	t := time.Now()
	c.Next()
	fmt.Printf("[%d] %s in %v", c.StatusCode, c.Req.RequestURI, time.Since(t))
}

var crosfun = func(c *golee.Context) {
	if origin := c.Req.Header.Get("Origin"); origin != "" {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		c.Writer.Header().Set("Access-Control-Allow-Headers",
			"x-token, content-type") //有使用自定义头 需要这个,Action, Module是例子
	}
	if c.Req.Method == "OPTIONS" {
		return
	}
	c.Next()
}

var login = func(c *golee.Context) {
	fmt.Println("login")

	username := c.PostForm("username")
	password := c.PostForm("password")
	fmt.Println("username: ", username)
	fmt.Println("password: ", password)

	var ad adminInfo
	if err := db.First(&ad, "Adminid = ? AND Password = ?", username, password).Error; err != nil {
		c.JSONResponse(golee.StatusOK, golee.H{
			"code":    60204,
			"message": "Account or Password are Incorrect.",
		})
		return
	}
	c.JSONResponse(golee.StatusOK, golee.H{
		"code": 20000,
		"data": map[string]string{"token": "admin-token"},
	})
}

var logout = func(c *golee.Context) {
	fmt.Println("logout")

	c.JSONResponse(golee.StatusOK, golee.H{
		"code": 20000,
		"data": "sucess",
	})
}

var getinfo = func(c *golee.Context) {
	fmt.Println("getinfo")
	// 获取key
	key := c.GET("admin-token")
	var ad adminInfo
	if err := db.First(&ad, "Key = ?", key).Error; err != nil {
		c.JSONResponse(golee.StatusOK, golee.H{
			"code":    60204,
			"message": "key error.",
		})
		return
	}
	c.JSONResponse(golee.StatusOK, golee.H{
		"code": 20000,
		"data": map[string]interface{}{
			"roles":        []string{"admin"},
			"introduction": "I am a super administrator",
			"avatar":       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
			"name":         "Super Admin",
		},
	})
}

var getAdmin = func(c *golee.Context) {
	fmt.Println("getAdmin")
	// 获取key
	key := c.GET("admin-token")
	fmt.Println(key)
	var ad adminInfo
	if err := db.First(&ad, "Key = ?", key).Error; err != nil {
		c.JSONResponse(golee.StatusOK, golee.H{
			"code":    60204,
			"message": "key error.",
		})
		return
	}
	// 获取数据库的内容
	var tableData []map[string]interface{}
	var users []adminInfo
	if err := db.Find(&users).Error; err != nil {
		c.JSONResponse(golee.StatusOK, golee.H{
			"code":    60204,
			"message": "Request Admin Error.",
		})
		return
	}
	for _, info := range users {
		tableData = append(tableData, map[string]interface{}{
			"adminid":   info.Adminid,
			"adminname": info.Adminname,
			"password":  info.Password,
			"limit":     info.Limit,
		})
	}
	c.JSONResponse(golee.StatusOK, golee.H{
		"code":      20000,
		"tableData": tableData,
	})
}

var getDevInfo = func(c *golee.Context) {
	// 获取key
	key := c.GET("admin-token")
	device := c.GET("device")
	var ad adminInfo
	if err := db.First(&ad, "Key = ?", key).Error; err != nil {
		c.JSONResponse(golee.StatusOK, golee.H{
			"code":    60204,
			"message": "key error.",
		})
		return
	}
	// 获取数据库的内容
	var tableData []map[string]interface{}
	var dev []Device
	if err := db.Where("devices_name = ?", device).Find(&dev).Error; err != nil {
		c.JSONResponse(golee.StatusOK, golee.H{
			"code":    60204,
			"message": "Request Devices Error.",
		})
		return
	}
	for _, info := range dev {
		var user User
		db.Where("id = ?", info.UserID).First(&user)
		tableData = append(tableData, map[string]interface{}{
			"id":     info.DeviceID,
			"name":   info.DevicesName,
			"user":   user.UserName,
			"status": info.DevicesStatus,
		})
	}
	c.JSONResponse(golee.StatusOK, golee.H{
		"code":      20000,
		"tableData": tableData,
	})

}

// 获取用户信息
var getUser = func(c *golee.Context) {
	fmt.Println("getUser")
	// 获取key
	key := c.GET("admin-token")
	fmt.Println(key)
	var ad adminInfo
	if err := db.First(&ad, "Key = ?", key).Error; err != nil {
		c.JSONResponse(golee.StatusOK, golee.H{
			"code":    60204,
			"message": "key error.",
		})
		return
	}
	// 获取数据库的内容
	var tableData []map[string]interface{}
	var users []User
	if err := db.Find(&users).Error; err != nil {
		c.JSONResponse(golee.StatusOK, golee.H{
			"code":    60204,
			"message": "Request Admin Error.",
		})
		return
	}
	for _, info := range users {
		tableData = append(tableData, map[string]interface{}{
			"username": info.UserName,
			"password": info.UserPassword,
		})
	}
	c.JSONResponse(golee.StatusOK, golee.H{
		"code":      20000,
		"tableData": tableData,
	})
}

var phLogin = func(c *golee.Context) {
	userid := c.GET("userid")
	password := c.GET("password")
	var user User
	if err := db.First(&user, "user_name = ? AND user_password = ?", userid, password).Error; err != nil {
		c.JSONResponse(golee.StatusOK, golee.H{
			"code":    60204,
			"message": "login error.",
		})
		return
	}
	c.JSONResponse(golee.StatusOK, golee.H{
		"code": 20000,
		"name": user.UserName,
		"key":  user.Key,
	})
}

var getDevices = func(c *golee.Context) {
	// 获取key
	key := c.GET("admin-token")
	var user User
	if err := db.First(&user, "Key = ?", key).Error; err != nil {
		c.JSONResponse(golee.StatusOK, golee.H{
			"code":    60204,
			"message": "key error.",
		})
		return
	}
	// name := c.GET("name")
	var tableData []map[string]interface{}
	// 查找当前发起请求的用户的信息
	// var tableData []map[string]interface{}
	// var user User
	// if err := db.Where("name = ?", name).First(&user).Error; err != nil {
	// 	c.JSONResponse(golee.StatusOK, golee.H{
	// 		"code":    60204,
	// 		"message": "name error.",
	// 	})
	// 	return
	// }
	// 寻找设备
	var devices []Device
	if err := db.Where("user_id = ?", user.ID).Find(&devices).Error; err != nil {
		c.JSONResponse(golee.StatusOK, golee.H{
			"code":    60204,
			"message": "search devices error.",
		})
		return
	}
	var (
		detype string
		color  string
		path   string
	)
	for _, info := range devices {
		if info.DevicesName == "智能锁" {
			detype = "lock"
			color = "#f596db"
			path = "../../static/img/device/lock.png"
		}
		if info.DevicesName == "台灯" {
			detype = "light"
			color = "#6dcd70"
			path = "../../static/img/device/light.png"
		}
		tableData = append(tableData, map[string]interface{}{
			"id":         info.DeviceID,
			"type":       detype,
			"color":      color,
			"title":      info.DevicesName,
			"title_more": info.DeviceInfo,
			"icon":       path,
		})
	}
	c.JSONResponse(golee.StatusOK, golee.H{
		"code":      20000,
		"tableData": tableData,
	})
}
